<?php
/**
 * Created by liuniukeji.com
 * User: 登录注册
 * Date: 16-3-31
 * @author:zhaojiping QQ: 17620286
 */

namespace User\Model;
use Common\Controller\CommonController;
use Think\Model;
use Common\Tools\Emchat;

class UserLoginModel extends Model{
    protected $tableName = 'User';
    //进行表单的合法性检测

    protected $_validate = array(
        array('phone', '11,11', '用户名称为11位手机号码', self::MUST_VALIDATE, 'length', 4), //登录时验证
        array('phone', 'check_username', '手机号码不正确', self::MUST_VALIDATE, 'callback', 4),
        array('password', '6,16', '用户密码长度有误 6-16位', self::MUST_VALIDATE, 'length', 4),
        );

    // 判断用户名是不是正确的手机号码
    protected function check_username($user_phone){
        if (!is_numeric($user_phone)) {
            return false;
        }
        return preg_match('/^1[3-8][0-9]{9}$/', $user_phone) ? true : false;
    }

    // 用户登录
    public function login($phone, $password){
        if (! $this->create(I('post.'), 4)) {
            return array('status' => 0,'msg' => $this->getError());
        }

        $where['phone'] = array('EQ', $phone);
        $user = $this->where($where)->find();

        //$user = M('Company')->where('id=')->select();
        if (!$user)
            return ['status' => 0, 'msg' => '用户名(手机号码)错误'];
        if ($user['status'] != 1)
            return ['status' => 0, 'msg' => '用户账号已被停用'];
        if ($user['password'] != md5($password))
            return ['status' => 0, 'msg' => '密码错误！'];
        $company=array();
        if(empty($user['company_id'])){
            $company=array();
        }else{
            if($user['level_id']==5){
                //企业用户
                $company = D('Company')->where('id='.$user['company_id'])->select();    
            }elseif($user['level_id']==1){
                //执法人员
                $array  = explode(',', $user['company_id']);
                if(count($array)<=1){
                    $company = D('Company')->where('id='.$user['company_id'])->select();    
                }else{
                    for($i=0;$i<count($array);$i++){
                        $company[$i] = D('Company')->where('id='.$array[$i])->find(); 
                        //print_r($company);   
                    }
                    //exit;
                }
                //echo count($array);exit;
                //$company = D('Company')->where('id='.$user['company_id'])->select();  
            }
        }
        $user['company']=$company;

        unset($user['push_id']);
        unset($user['password']);
        unset($user['parent_id']);
        unset($user['status']);
        unset($user['object_ids']);
        return ['status' => 1, 'msg' => $user];
    }
}
